import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from datetime import datetime


class EmailManage:
    def __init__(self, smtp_server='smtp.qq.com', smtp_port=465,
                 sender='3439889674@qq.com', password='dngjupezkplqcijc', 
                 receiver='hyyocean1@gmail.com', timeout=120):
        """
        初始化邮件管理器
        
        Args:
            smtp_server: SMTP服务器地址
            smtp_port: SMTP端口
            sender: 发送者邮箱
            password: 邮箱授权码
            receiver: 接收者邮箱
            timeout: 连接超时时间（秒）
        """
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.sender = sender
        self.password = password
        self.receiver = receiver
        self.timeout = timeout

    def send_email(self, subject, content, attachments=None, content_type='html'):
        """
        发送邮件的通用方法
        
        Args:
            subject: 邮件主题
            content: 邮件内容
            attachments: 附件列表 [{'path': '文件路径', 'name': '显示名称'}]
            content_type: 内容类型 'html' 或 'plain'
        
        Returns:
            bool: 发送成功返回True，失败返回False
        """
        try:
            # 创建邮件对象
            msg = MIMEMultipart()
            msg['From'] = self.sender
            msg['To'] = self.receiver
            msg['Subject'] = subject
            
            # 添加邮件内容
            msg.attach(MIMEText(content, content_type, 'utf-8'))
            
            # 添加附件
            if attachments:
                for attachment in attachments:
                    if os.path.exists(attachment['path']):
                        with open(attachment['path'], 'rb') as f:
                            part = MIMEBase('application', 'octet-stream')
                            part.set_payload(f.read())
                            encoders.encode_base64(part)
                            part.add_header(
                                'Content-Disposition',
                                f'attachment; filename= {attachment["name"]}'
                            )
                            msg.attach(part)
            
            # 连接SMTP服务器并发送邮件
            if self.smtp_port == 465:
                # 使用SSL连接（适用于端口465）
                server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, timeout=self.timeout)
            else:
                # 使用普通连接然后启用TLS（适用于端口587等）
                server = smtplib.SMTP(self.smtp_server, self.smtp_port, timeout=self.timeout)
                server.starttls()  # 启用TLS加密
            
            server.login(self.sender, self.password)
            server.send_message(msg)
            server.quit()
            
            return True
            
        except Exception as e:
            print(f"发送邮件失败: {e}")
            # 记录更详细的错误信息用于调试
            import traceback
            print(f"详细错误信息: {traceback.format_exc()}")
            return False

    def send_jenkins_build_notification(self, build_status, build_number, build_url='', console_log=''):
        """
        发送Jenkins构建通知邮件
        
        Args:
            build_status: 构建状态 SUCCESS/FAILURE/UNSTABLE
            build_number: 构建编号
            build_url: 构建URL
            console_log: 控制台日志摘要
        
        Returns:
            bool: 发送成功返回True，失败返回False
        """
        # 根据构建状态设置邮件样式
        status_config = {
            'SUCCESS': {
                'color': '#28a745',
                'icon': '✅',
                'title': '构建成功',
                'message': '恭喜！构建和测试都已成功完成。'
            },
            'FAILURE': {
                'color': '#dc3545', 
                'icon': '❌',
                'title': '构建失败',
                'message': '构建过程中出现错误，请及时处理。'
            },
            'UNSTABLE': {
                'color': '#ffc107',
                'icon': '⚠️', 
                'title': '构建不稳定',
                'message': '构建完成但存在一些问题，建议检查。'
            }
        }
        
        config = status_config.get(build_status, status_config['FAILURE'])
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        # 构建邮件主题
        subject = f"[{config['icon']} {config['title']}] 乐抽云项目 - 构建 #{build_number}"
        
        # 构建HTML邮件内容
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body {{ font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }}
                .container {{ max-width: 600px; margin: 0 auto; background-color: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
                .header {{ background-color: {config['color']}; color: white; padding: 20px; text-align: center; }}
                .content {{ padding: 20px; }}
                .status-badge {{ display: inline-block; padding: 5px 15px; border-radius: 20px; color: white; background-color: {config['color']}; font-weight: bold; }}
                .info-table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
                .info-table th, .info-table td {{ padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }}
                .info-table th {{ background-color: #f8f9fa; font-weight: bold; }}
                .console-log {{ background-color: #f8f9fa; padding: 15px; border-radius: 5px; font-family: monospace; font-size: 12px; white-space: pre-wrap; max-height: 200px; overflow-y: auto; }}
                .footer {{ background-color: #f8f9fa; padding: 15px; text-align: center; color: #666; }}
                .btn {{ display: inline-block; padding: 10px 20px; background-color: {config['color']}; color: white !important; text-decoration: none !important; border-radius: 5px; margin: 5px; border: none; cursor: pointer; }}
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>{config['icon']} 乐抽云项目构建通知</h1>
                    <p>{config['message']}</p>
                </div>
                
                <div class="content">
                    <h2>构建信息</h2>
                    <table class="info-table">
                        <tr>
                            <th>构建状态</th>
                            <td><span class="status-badge">{build_status}</span></td>
                        </tr>
                        <tr>
                            <th>构建编号</th>
                            <td>#{build_number}</td>
                        </tr>
                        <tr>
                            <th>构建时间</th>
                            <td>{current_time}</td>
                        </tr>
                        <tr>
                            <th>项目名称</th>
                            <td>乐抽云项目 (lottery-system)</td>
                        </tr>
                    </table>
                    
                    {self._generate_action_buttons(build_url) if build_url else ''}
                    
                    {f'<h3>控制台日志摘要</h3><div class="console-log">{console_log}</div>' if console_log else ''}
                </div>
                
                <div class="footer">
                    <p>此邮件由Jenkins自动发送 | 乐抽云项目自动化测试系统</p>
                    <p>发送时间: {current_time}</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        return self.send_email(subject, html_content, content_type='html')

    def _generate_action_buttons(self, build_url):
        """
        生成操作按钮的HTML
        
        Args:
            build_url: Jenkins构建URL
            
        Returns:
            str: 按钮HTML字符串
        """
        if not build_url:
            return ''
            
        # 确保URL格式正确
        if not build_url.startswith('http'):
            build_url = f'http://localhost:8080/job/lottery-system/{build_url}'
        
        # 移除末尾的斜杠
        build_url = build_url.rstrip('/')
        
        return f'''
        <h3>快速操作</h3>
        <div style="margin: 15px 0;">
            <a href="{build_url}" class="btn" target="_blank" style="text-decoration: none;">🔍 查看构建详情</a>
            <a href="{build_url}/console" class="btn" target="_blank" style="text-decoration: none;">📋 查看控制台日志</a>
        </div>
        '''

    def send_test_report(self, report_path, test_results=None):
        """
        发送测试报告邮件
        
        Args:
            report_path: 测试报告文件路径
            test_results: 测试结果摘要
        
        Returns:
            bool: 发送成功返回True，失败返回False
        """
        subject = "乐抽云项目自动集成测试报告"
        
        content = f"""
        <h2>乐抽云项目测试报告</h2>
        <p>测试执行时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        
        {f'<h3>测试结果摘要</h3><pre>{test_results}</pre>' if test_results else ''}
        
        <p>详细测试报告请查看附件。</p>
        """
        
        attachments = []
        if report_path and os.path.exists(report_path):
            attachments.append({
                'path': report_path,
                'name': 'test_report.html'
            })
        
        return self.send_email(subject, content, attachments, content_type='html')

    def seand_email(self):
        """
        保持向后兼容的原始方法（修正拼写错误）
        """
        try:
            # 尝试读取report.html文件
            report_content = ""
            if os.path.exists('report.html'):
                with open('report.html', 'r', encoding='utf-8') as f:
                    report_content = f.read()
            else:
                report_content = "<p>测试报告文件未找到</p>"
            
            return self.send_email(
                subject='乐抽云项目自动集成测试报告',
                content=report_content,
                content_type='html'
            )
        except Exception as e:
            print(f"发送邮件失败: {e}")
            return False